<template>
  <div>
    <el-button :disabled="visible" @click="showDialog">{{ buttonName }}</el-button>
    <a-modal v-model="visible" title="批量导入" wrap-class-name="BatchImport" centered :mask-closable="false" :footer="null" @cancel="handleCancel">
      <template v-if="impStep === 1">
        <div class="text-center fw-6 fs-18 cl-000 mt-20 mb-20">请上传需要导入的文件</div>
        <div class="mbody">
          <div class="">
            <el-upload
              ref="upload"
              action=""
              class="upload-demo"
              accept=".xls,.xlsx"
              :http-request="upload"
              :on-remove="fileRemove"
              :on-change="filechange"
              :limit="1"
              :on-exceed="handleExceed"
              :file-list="fileList"
              :auto-upload="false"
            >
              <el-button icon="el-icon-upload">本地上传</el-button>
              <div slot="tip" class="el-upload__tip mt-20">
                <p>支持扩展名：.xls .xlsx，文件大小请控制在 5MB 以内</p>
                <p>
                  如没有模板，请下载
                  <a class="imp_download" :href="downloadUrlHerf" :download="downloadUrl">导入模板</a>
                </p>
              </div>
            </el-upload>
          </div>
        </div>
      </template>
      <template v-else-if="impStep === 2">
        <div class="step_error">
          <div class="notice">
            <a-icon type="exclamation-circle" style="fontSize:50px;color:#FAAD14" theme="filled" />
            <p>校验异常</p>
          </div>
          <p class="sub_notice">
            本次结果：共校验 <span class="text_b">{{ totalSize }}</span> 条记录， 其中 <span class="text_r">{{ errorSize }}</span> 条记录出错
          </p>
          <p class="sub_notice">请先下载文件修改，再重新导入修改后的文件</p>
        </div>
      </template>
      <template v-else-if="impStep === 3">
        <div class="step_error">
          <div class="notice">
            <a-icon type="check-circle" style="fontSize:50px;color:#52C51A" theme="filled" />
            <p>批量导入成功</p>
          </div>
          <p class="sub_notice">
            本次结果：共导入 <span class="text_b">{{ totalSize }}</span> 条记录， <span class="text_b">{{ totalSize }}</span> 条记录已成功导入
          </p>
        </div>
      </template>
      <div class="text-center mt-20">
        <template v-if="impStep === 1">
          <el-button key="submit" type="primary" :disabled="disableBtn" @click="handleOk">确认导入</el-button>
        </template>
        <template v-else-if="impStep === 2">
          <!-- <el-button key="back" @click="handleCancel">关闭</el-button> -->
          <el-button key="submit" type="primary" @click="handleDownload">下载文件</el-button>
        </template>
        <template v-else-if="impStep === 3">
          <el-button key="submit" type="primary" @click="handleCancel">完 成</el-button>
        </template>
      </div>
    </a-modal>
  </div>
</template>
<script>
import { uploadExcel } from '@/api/file/upload'
import { message } from 'ant-design-vue'
import { crud } from '@crud/crud'
const ExportJsonExcel = require('js-export-excel')
const key = 'updatable'
export default {
  name: 'IndexUpdate',
  mixins: [crud()],
  props: {
    uploadUrl: {
      // Demo  supplier/goods/category/importInBatch
      // 上传文件地址
      type: String,
      default: ''
    },
    buttonName: {
      type: String,
      default: '批量导入物流信息'
    },
    downloadUrl: {
      // 下载模板地址
      type: String,
      default: ''
    },
    downloadUrlHerf: {
      type: String,
      default: ''
    },
    sheetHeaderArr: {
      type: Array,
      default: null
    }, // 校验失败的表头 Demo ['一级类目名称', '二级类目名称', '失败原因']
    sortByprop: {
      type: Array,
      default: null
    } // 校验失败的字段排序，需要和 sheetHeaderArr对齐
  },
  data() {
    return {
      file: null,
      visible: false,
      disableBtn: true,
      impStep: 1, // 导入状态
      totalSize: 0, // 导入条数
      errorSize: 0, // 错误条数
      fileList: [],
      ExcelDataDTOList: []
      // stepMap: [{ msg: '下载导入模板' }, { msg: '按模板填写' }, { msg: '上传文件' }, { msg: '完成' }]
    }
  },
  methods: {
    // 下载文件
    showDialog() {
      this.visible = true
    },
    handleDownload() {
      const option = {}
      option.fileName = this.file.name.split('.')[0] + new Date().getTime()
      const columns = Object.keys(this.ExcelDataDTOList[0])
      console.log('this.ExcelDataDTOList[0]=', this.ExcelDataDTOList[0])
      console.log('this.columns=', columns)
      option.datas = [
        {
          sheetData: this.ExcelDataDTOList,
          sheetName: 'list', // Excel文件sheel名称
          sheetFilter: columns,
          sheetHeader: this.sheetHeaderArr,
          columnWidths: columns.map(() => 20)
        }
      ]
      const toExcel = new ExportJsonExcel(option)
      toExcel.saveExcel()
    },
    // 触发上传
    handleOk(e) {
      this.$refs.upload.submit()
    },
    // 关闭弹窗
    handleCancel() {
      this.visible = false
      this.impStep = 1
      this.disableBtn = true
      this.fileRemove()
      this.crud.refresh()
      this.crud.toDefault()
      this.$refs.upload && this.$refs.upload.clearFiles()
    },
    // 超限钩子
    handleExceed(files, fileList) {
      this.$message.error('最多上传一个文件')
    },
    // 文件改变
    filechange(file, fileList) {
      console.log('filechange,file=', file)
      console.log('filechange,fileList=', fileList)
      if (fileList.length > 0) {
        this.disableBtn = false
      } else {
        this.disableBtn = true
      }
    },
    // 文件移出
    fileRemove(file, fileList) {
      this.disableBtn = true
    },
    // 文件大小校验
    sizeCheck(file) {
      const isLt5M = file.size / 1024 / 1024 < 5
      return isLt5M
    },
    // 上传文件
    upload() {
      if (this.sizeCheck(this.$refs.upload.uploadFiles[0])) {
        const file = this.$refs.upload.uploadFiles[0].raw
        const formData = new FormData()
        formData.append('file', file)
        this.visible = false
        message.loading({ content: '正在校验数据...', key })
        uploadExcel(this.uploadUrl, formData)
          .then(res => {
            message.destroy()
            if (res.errorCode === 0) {
              this.errorSize = res.data.errorSize
              this.totalSize = res.data.totalSize
              message.loading({
                content: `正在导入...`,
                key,
                onClose: () => {
                  this.$refs.upload.clearFiles()
                  this.impStep = 3
                  this.visible = true
                }
              })
            }
          })
          .catch(e => {
            message.destroy()
            if (e.errorCode === 30001011) {
              this.file = file
              this.errorSize = e.data.errorSize
              this.totalSize = e.data.totalSize
              this.impStep = 2
              this.visible = true
              const excelList = []
              let params = {}
              Object.keys(e.data).forEach(item => {
                const arr = e.data[item]
                if (Array.isArray(arr)) {
                  // 拿到数组对象
                  arr.forEach(item2 => {
                    const arrKey = Object.keys(item2)
                    arrKey.map(item3 => {
                      params[item3] = item2[item3]
                    })
                    params.reason && delete params.reaso && (params.reason = item2.reason ? item2.reason : '')
                    excelList.push(params)
                    params = {}
                  })
                }
              })
              // if(this.sortByprop.length>0){
              //   excelList.filter()
              // }
              console.log('sortByprop=', this.sortByprop)
              // debugger
              this.ExcelDataDTOList = excelList
              // if (this.batchType === 0) {
              //   const excelList = []
              //   e.data.brandExcelDataDTOList.map(res => {
              //     excelList.push({ name: res.name || '', reason: res.reason || '' })
              //   })
              //   this.ExcelDataDTOList = excelList
              // } else if (this.batchType === 1) {
              //   const excelList = []
              //   e.data.categoryExcelDataDTOList.map(res => {
              //     excelList.push({
              //       firstCategoryName: res.firstCategoryName || '',
              //       secondCategoryName: res.secondCategoryName || '',
              //       reason: res.reason || ''
              //     })
              //   })
              //   this.ExcelDataDTOList = excelList
              // }
            }
          })
      } else {
        this.$message.error('请重新上传文件,文件大小控制在 5MB 以内！')
      }
    }
  }
}
</script>
<style rel="stylesheet/scss" lang="scss" scoped>
/deep/ .BatchImport {
  .el-upload__tip {
    p {
      margin-bottom: 5px;
    }
    .imp_download {
      color: #1a90ff;
    }
  }

  .ant-modal-header {
    border-bottom: 1px solid transparent;
    .ant-modal-title {
      font-size: 15px;
    }
  }
  .ant-modal-body {
    padding: 10px 20px 40px 20px;
    height: auto;
    min-height: 250px;
    .step {
      ul {
        display: flex;
        justify-content: space-around;
        li {
          display: flex;
          align-items: center;

          div {
            color: #d9d9d9;
            border: 1px solid #d9d9d9;
            box-sizing: border-box;
            width: 30px;
            height: 30px;
            display: flex;
            align-items: center;
            justify-content: center;
            border-radius: 50%;
          }
          span {
            padding-left: 8px;
          }
        }
      }
    }
    .step_error {
      padding: 24px;
      .notice {
        display: flex;
        flex-direction: column;
        align-items: center;
        justify-content: center;
        p {
          margin-top: 20px;
          font-size: 20px;
          font-weight: bolder;
        }
      }
      .sub_notice {
        text-align: center;
        margin-bottom: 3px;
        .text_b {
          color: #1a90ff;
        }
        .text_r {
          color: #f04764;
        }
      }
    }
    .mbody {
      // display: flex;
      text-align: center;
      padding: 0 24px;
      .label {
        width: 70px;
        padding-top: 5px;
      }
    }
  }
}
</style>
